package diona

import auth.GoogleOperations
import model._
import net.liftweb.http.rest.RestHelper
import javax.imageio.ImageIO
import java.awt.image.BufferedImage
import java.io._
import net.liftweb.util.BasicTypesHelpers.AsLong
import net.liftweb.common.{Box, Full}
import net.liftweb.http.auth.AuthRole
import net.liftweb.http._
import net.liftweb.json._
import Extraction._

/**
 * User: anton
 * Date: 20.02.11 22:22
 */
class PublisherRestHelper extends RestHelper
{

  def protection: LiftRules.HttpAuthProtectedResourcePF =
  {
    case Req("api" :: _, _, _) => {
      Full(AuthRole("Default"))
    }
  }

  serve {
    case Put("api" :: "images" :: "add" :: _, req) => saveImage(req)
    case Get("api" :: "content" :: "picasa" :: _, req) => getPicasaContent(req)
    case Req("api" :: "auth" :: _, _, _) => new OkResponse()
    case Req("imageViewer" :: "image" :: AsLong(image) :: Nil, "jpg", GetRequest) => getImage(image)
  }

  private def saveImage(r: Req): Box[LiftResponse] =
  {
    for {
      groupId <- r.param("groupId") ?~ "groupId parameter missing" ~> 400
    } yield {
      val user = CurrentUser.get
      val image: BufferedImage = ImageIO.read(new ByteArrayInputStream(r.body.get))
      ImageInfo.save(image, user, groupId)
      OkResponse()
    }
  }

  private case class PhotoInfo(photoId: String, uri: String)

  private def getPicasaContent(r: Req): Box[LiftResponse] =
  {
    Some(JsonResponse(
      decompose(
        GoogleOperations.getPhotos(CurrentUser.get).map(e => PhotoInfo(e.getGphotoId, GoogleOperations.getUri(e)))
      )
    )
    )
  }

  private def getImage(image: Long): StreamingResponse =
  {
    val imageInfo = ImageInfo.byId(image).get
    val headers = ("Content-type" -> "image/jpeg") :: Nil
    val imageFile = new File(imageInfo.dir.is, imageInfo.file.is)
    val is = ImageIO.createImageInputStream(imageFile)
    return StreamingResponse(is, is.close _, is.length(), headers, Nil, 200)
  }
}